from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from signup.forms import SignupForm
from signup.forms import LoginForm
from django.contrib.auth import authenticate
from django.contrib.auth import login
from django.contrib.auth import logout
from bankaccount.models import BankAccount


def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST,request.FILES)
        if form.is_valid():
            # create new user
            form.save()
            return HttpResponseRedirect("/login/")
    else:
        username = action = request.GET.get('username', '')
        form = SignupForm(initial={'username': username,'email':username+'@'})
    return render_to_response('signup/signup.html',
    { 'form': form })

def loginView(request):
    loginViewError=''
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            # login operation
            username = request.POST['username']  
            password = request.POST['password']  
            user = authenticate(username=username, password=password)  
            if user is not None:  
                if user.is_active:  
                    login(request, user)  
                    return HttpResponseRedirect("/people/"+username+"/")  
                else:  
                    loginViewError = 'User name or password is wrong.'
            else:
                loginViewError = 'User doesn\'t exists.'
    else:
        form = LoginForm()
    return render_to_response('login/login.html',
    { 'form': form, 'loginViewError': loginViewError})
        
def logoutView(request):
    logout(request)
    return HttpResponseRedirect("/login/")
